<template>
  <div class="app-container">
    <h2 class="data-list-title" style=" margin-bottom: 5px;margin-top: 0; color: #6495ED; font-family: 'Roboto', 'Arial Narrow', sans-serif; font-weight: 500;">
      <i class="el-icon-search"></i>
        搜索条件
    </h2>
    <div style="border-bottom: 2px solid #6495ED;margin-top: 0px;margin-bottom: 10px;"></div>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" label-position="left">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="房间名称" prop="roomName">
            <el-input
              v-model="queryParams.roomName"
              placeholder="请输入房间名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="省份" prop="province">
            <el-select v-model="queryParams.province" placeholder="请选择省份" clearable @change="changeCityListQuery($event)">
              <el-option
                v-for="province in provinceListQuery"
                :key="province.id"
                :label="province.name"
                :value="province.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="城市" prop="city">
            <el-select v-model="queryParams.city" placeholder="请选择城市" clearable @change="changeCountyListQuery($event)" :disabled="!queryParams.province">
              <el-option
                v-for="city in cityListQuery"
                :key="city.id"
                :label="city.name"
                :value="city.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="区/县" prop="county">
            <el-select v-model="queryParams.county" placeholder="请选择区/县" clearable :disabled="!queryParams.city">
              <el-option
                v-for="county in countyListQuery"
                :key="county.id"
                :label="county.name"
                :value="county.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="具体位置" prop="roomLocation">
            <el-input
              v-model="queryParams.roomLocation"
              placeholder="请输入房间具体位置"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="月租" prop="monthlyRent">
            <el-input
              v-model="queryParams.monthlyRent"
              placeholder="请输入月租"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option
                v-for="dict in room_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-divider content-position="center" style="margin: 0px 0;"></el-divider>
    <h2 class="data-list-title" style=" margin-bottom: 5px; color: #6495ED; font-family: 'Roboto', 'Arial Narrow', sans-serif; font-weight: 500;">
      <i class="el-icon-search"></i>
        房间信息
    </h2>
    <div style="border-bottom: 2px solid #6495ED;margin-top: 0px;margin-bottom: 10px;"></div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['room:room:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['room:room:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['room:room:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['room:room:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="房间ID" align="center" prop="roomId" />
      <el-table-column label="房间名称" align="center" prop="roomName" />
      <el-table-column label="省份" align="center" prop="province" />
      <el-table-column label="城市" align="center" prop="city" />
      <el-table-column label="区/县" align="center" prop="county" />
      <el-table-column label="具体位置" align="center" prop="roomLocation" />
      <el-table-column label="月租" align="center" prop="monthlyRent" >
        <template #default="scope">
          <div>
            ¥{{ scope.row.monthlyRent }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="room_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['room:room:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['room:room:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改房间管理对话框 -->
    <el-dialog :title="title" v-model="open" width="530px" append-to-body >
      <el-form ref="roomRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="房间名称" prop="roomName">
          <el-input v-model="form.roomName" placeholder="请输入房间名称" />
        </el-form-item>
        
        <el-form-item label="省份" prop="province">
          <el-select v-model="form.province" placeholder="请选择省份"
          @change="changeCityList($event)">
            <el-option
              v-for="province in provinceList"
              :key="province.id"
              :label="province.name"
              :value="province.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select v-model="form.city" placeholder="请选择城市" :disabled="!form.province"
          @change="changeCountyList($event)">
            <el-option
              v-for="city in cityList"
              :key="city.id"
              :label="city.name"
              :value="city.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区/县" prop="county">
          <el-select v-model="form.county" placeholder="请选择区/县" :disabled="!form.city">
            <el-option
              v-for="county in countyList"
              :key="county.id"
              :label="county.name"
              :value="county.name"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="房间具体位置" prop="roomLocation">
          <el-input v-model="form.roomLocation" placeholder="请输入房间具体位置" />
        </el-form-item>
        <el-form-item label="月租" prop="monthlyRent">
          <el-input v-model="form.monthlyRent" placeholder="请输入月租" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in room_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-divider content-position="center">房间类型信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddRoomType">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteRoomType">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="roomTypeList" :row-class-name="rowRoomTypeIndex" @selection-change="handleRoomTypeSelectionChange" ref="roomType">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="类型名称" prop="typeName" width="200">
            <template #default="scope">
              <!-- <el-input v-model="scope.row.typeName" placeholder="请输入类型名称" /> -->
              <el-select v-model="scope.row.typeName" placeholder="请选择类型名称"
                @change="changeTypeValueList(scope.row)">
                <el-option
                  v-for="type in typeList"
                  :key="type.name"
                  :label="type.name"
                  :value="type.name"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="类型值" prop="typeValue" width="200">
            <template #default="scope">
              <!-- <el-input v-model="scope.row.typeValue" placeholder="请输入类型值" /> -->
               <!-- multiple：把它变成复选框 -->
              <el-select v-model="scope.row.typeValue" placeholder="请选择类型值" 
              @click.native="clickChangeTypeValueList(scope.row)">
                <el-option
                  v-for="value in typeValueList"
                  :key="value"
                  :label="value"
                  :value="value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Room">
import { listRoom, getRoom, delRoom, addRoom, updateRoom } from "@/api/room/room";

//----------------------------------------------------------
// 定义房间类型名称和类型列表的静态数据
const typeList=ref([
  {name:"户型",value:["单间","一室一厅","两室一厅","三室一厅"]},
  {name:"朝向",value:["朝南","朝北","朝东","朝西","南北朝向","东西朝向"]},
  {name:"楼层",value:["1楼","2楼","3楼","4楼","5楼","6楼","7楼","8楼","9楼","10楼","11楼","12楼","13楼","14楼","15楼","16楼","17楼","18楼","19楼","20楼","21楼","22楼","23楼","24楼","25楼","26楼","27楼","28楼","29楼","30楼","31楼"]}
]);
//存储type_value列表数组
const typeValueList=ref([])

// 修改时解决类型值无数据的问题
function getTypeValueList(row){
  // 根据选中的name去查找对应的Value
  typeValueList.value=typeList.value.find(item=>item.name==row.typeName).value;
}

// 定义改变类型名称时改变类型值列表
function changeTypeValueList(row){
  // 清空已填的typeValue
  row.typeValue=[];
  // 根据选中的name去查找对应的Value
  typeValueList.value=typeList.value.find(item=>item.name==row.typeName).value;
}

// 解决不改变类型名称，修改类型值列表时数据源为空的问题
function clickChangeTypeValueList(row){
  typeValueList.value=typeList.value.find(item=>item.name==row.typeName).value;
}
//----------------------------------------------------------

//----------------------------------------
//新模块声明：
const imageApartmentList = ref([]);

//----------------------------------------

const { proxy } = getCurrentInstance();
const { room_status } = proxy.useDict('room_status');

const roomList = ref([]);
const roomTypeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedRoomType = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roomName: null,
    province: null,
    city: null,
    county: null,
    roomLocation: null,
    monthlyRent: null,
    status: null,
  },
  rules: {
    roomName: [
      { required: true, message: "房间名称不能为空", trigger: "blur" }
    ],
    province: [
      { required: true, message: "省份不能为空", trigger: "blur" }
    ],
    city: [
      { required: true, message: "城市不能为空", trigger: "blur" }
    ],
    county: [
      { required: true, message: "区/县不能为空", trigger: "blur" }
    ],
    roomLocation: [
      { required: true, message: "房间具体位置不能为空", trigger: "blur" }
    ],
    monthlyRent: [
      { required: true, message: "月租不能为空", trigger: "blur" },
      { validator: (rule, value, callback) => {
          if (value && !/^\d+$/.test(value)) {
            callback(new Error('月租必须为数字'));
          } else {
            callback();
          }
        }, trigger: 'blur' 
      }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询房间管理列表 */
function getList() {
  loading.value = true;
  listRoom(queryParams.value).then(response => {
    roomList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    roomId: null,
    roomName: null,
    province: null,
    city: null,
    county: null,
    roomLocation: null,
    monthlyRent: null,
    status: null,
    createTime: null,
    updateTime: null
  };
  roomTypeList.value = [];
  imageApartmentList.value = [];
  proxy.resetForm("roomRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.roomId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加房间管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _roomId = row.roomId || ids.value
  getRoom(_roomId).then(response => {
    form.value = response.data;
    roomTypeList.value = response.data.roomTypeList;
    imageApartmentList.value = response.data.imageApartmentList;
    //将类型值列表的value转为JSON字符串数组
    if(roomTypeList.value!=null){
      roomTypeList.value.forEach(item=>{
          item.typeValue=JSON.parse(item.typeValue)
      });
    }
    open.value = true;
    title.value = "修改房间管理";
    // 在获取数据后初始化城市列表和区县列表
    getCityListByName(form.value.province);
    getCountyListByName(form.value.city);
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roomRef"].validate(valid => {
    if (valid) {
      form.value.roomTypeList = roomTypeList.value;
      form.value.imageApartmentList = imageApartmentList.value;
      // 将value列表通过JSON工具转为字符串
      if(form.value.roomTypeList!=null){
        form.value.roomTypeList.forEach(item=>{
        item.typeValue=JSON.stringify(item.typeValue)
      });
      }
      if (form.value.roomId != null) {
        updateRoom(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRoom(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _roomIds = row.roomId || ids.value;
  proxy.$modal.confirm('是否确认删除房间管理编号为"' + _roomIds + '"的数据项？').then(function() {
    return delRoom(_roomIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 房间类型序号 */
function rowRoomTypeIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 房间类型添加按钮操作 */
function handleAddRoomType() {
  let obj = {};
  obj.typeName = "";
  obj.typeValue = "";
  roomTypeList.value.push(obj);
}

/** 房间类型删除按钮操作 */
function handleDeleteRoomType() {
  if (checkedRoomType.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的房间类型数据");
  } else {
    const roomTypes = roomTypeList.value;
    const checkedRoomTypes = checkedRoomType.value;
    roomTypeList.value = roomTypes.filter(function(item) {
      return checkedRoomTypes.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleRoomTypeSelectionChange(selection) {
  checkedRoomType.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('room/room/export', {
    ...queryParams.value
  }, `room_${new Date().getTime()}.xlsx`)
}

getList();

//----------------------------------------
//省市县功能实现：
import { listTopCity, cityListByName } from "@/api/district/district";

const provinceList = ref([]);
const cityList = ref([]);
const countyList = ref([]);
/*
增加修改对话框省市县功能实现：
*/
// 获取增加修改对话框省份列表
function getProvinceList() {
  listTopCity().then(response => {
    provinceList.value = response.rows;
  });
}

// 增加修改对话框根据省份名字获取城市列表
function getCityListByName(provinceName){
  cityListByName({name:provinceName}).then(response=>{
    cityList.value = response.rows;
  })
}

// 增加修改对话框根据城市名字获取区县列表
function getCountyListByName(cityName){
  cityListByName({name:cityName}).then(response=>{
    countyList.value = response.rows;
  })
}

// 增加修改对话框改变城市列表
function changeCityList(provinceName){
  form.value.city = null;
  form.value.county = null;
  getCityListByName(provinceName);
}

// 增加修改对话框改变区县列表
function changeCountyList(cityName){
  form.value.county = null;
  getCountyListByName(cityName);
}

// 初始化获取增加修改对话框省份列表
getProvinceList();
// 初始化获取增加修改对话框城市列表和区县列表
getCityListByName(form.value.province);
// 初始化获取增加修改对话框区县列表
getCountyListByName(form.value.city);

/*
搜索框省市县功能实现：
*/
const provinceListQuery = ref([]);
const cityListQuery = ref([]);
const countyListQuery = ref([]);
// 获取搜索框省份列表
function getProvinceQueryList() {
  listTopCity().then(response => {
    provinceListQuery.value = response.rows;
  });
}

// 搜索框根据省份名字获取城市列表
function getCityListQueryByName(provinceName){
  
  cityListByName({name:provinceName}).then(response=>{
    cityListQuery.value = response.rows;  
  })
}
// 搜索框根据城市名字获取区县列表
function getCountyListQueryByName(cityName){
  //打印cityName
  
  cityListByName({name:cityName}).then(response=>{
    countyListQuery.value = response.rows;
  })
}

// 改变搜索框城市列表
function changeCityListQuery(provinceName){
  queryParams.value.city = null;
  queryParams.value.county = null;
  getCityListQueryByName(provinceName);
}
// 改变搜索框区县列表
function changeCountyListQuery(cityName){
  queryParams.value.county = null;
  getCountyListQueryByName(cityName);
}
// 初始化获取搜索框省份列表
getProvinceQueryList();
// 初始化获取搜索框城市列表
getCityListQueryByName(queryParams.value.province);
// 初始化获取搜索框区县列表
getCountyListQueryByName(queryParams.value.city);

//----------------------------------------


</script>
